'''
Created on 27/03/2009

@author: eh01
'''
from yarra.datastore import dsconstants
from yarra.datastore.dsstub import DSStub
from yarra.datastore.dst import DST
from yarra.event.event import Event
from yarra.event.eventhandler import BaseEventHandler
from yarra.event.eventmanager import EventManager


class HubMessageHandler(BaseEventHandler):
    '''
    Handles all messages that come from the hub and delegates to the appropriate handler
    '''


    def __init__(self):
        '''
        Constructor
        '''
    
    def do(self, data):
        dso = data
        
        # get message type
        message_type_dst = dso.get_dst(dsconstants.SUBJECT_ROOT, 
                   dsconstants.PREDICATE_MESSAGE_TYPE)
        message_type = message_type_dst.get_literal()
        
        # get requesting node details
        message_request_node_id_dst = dso.get_dst(dsconstants.SUBJECT_ROOT, 
                    dsconstants.PREDICATE_MESSAGE_REQUEST_NODE_ID)
        message_request_node_id = message_request_node_id_dst.get_literal()
        dsstub = DSStub()
        message_request_node = dsstub.get_node_name_by_node_id(message_request_node_id)
        message_request_node_dst = DST(subject=dsconstants.SUBJECT_ROOT, 
                    predicate=dsconstants.PREDICATE_MESSAGE_REQUEST_NODE, 
                    literal=message_request_node)
        
        # update dso
        dso.remove_dst(message_type_dst)
        dso.remove_dst(message_request_node_id_dst)
        dso.add_dst(message_request_node_dst)
        
        # add event
        event_type = message_type + "_event_type"
        event = Event(event_type, dso)
        EventManager().add_event(event)
                